var gulp = require('gulp');
const del = require('del');
const { src, dest, series, parallel, watch } = require('gulp');
const ts = require('gulp-typescript');
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-sass');

const tsProject = ts.createProject('tsconfig.json');

const destDir = 'dist';
const sourceDir = 'src';

const styleSource = `${sourceDir}/**/*.scss`;
const otherSource = `${sourceDir}/**/*.!(scss|ts|tsx)`;
const scriptSource = `${sourceDir}/**/*.+(ts|tsx)`;

const sourceMapOutDir = '.';
const sourceMapOptions = { includeContent: false, sourceRoot: '../src' };

// 删除dist目录
function cleanDist() {
    return del(`${destDir}/**`);
}

// 复制除源码外的其他文件到指定路径
function copyResources() {
    return src(otherSource).pipe(dest(destDir));
}

// 编译ts文件 强制eslint 包含ts和d.ts的sourcemap
function compileScript() {
    return tsProject
        .src()
        .pipe(tsProject())
        .pipe(dest(destDir));
}

// 编译scss文件 强制stylelint 包含css的sourcemap
function compileStyle() {
    return src(styleSource)
        .pipe(sourcemaps.init())
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(sourcemaps.write(sourceMapOutDir, sourceMapOptions))
        .pipe(dest(destDir));
}

// 完整编译 先clean, 然后并行: 复制资源 编译scss 编译ts
let compile = series(cleanDist, parallel(copyResources, compileScript, compileStyle));
exports.compile = compile;

compile.compileStyle = compileStyle;
compile.compileScript = compileScript;




exports.watch = function () {
    gulp.watch(styleSource, compile.compileStyle);
    gulp.watch(scriptSource, compile.compileScript);
}

// 默认任务是编译
exports.default = compile;
// exports.default = series(cleanDist, parallel(compileStyle));;